<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Config;

class Order extends BaseController
{
    /**
     * 创建订单
     */
    public function createOrder()
    {
        $memberId = $this->getMemberIdFromToken();

        if (!$memberId) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $carNumber = $this->request->param('car_number', '');
        $planName = $this->request->param('plan_name', '');
        $deposit = (int)$this->request->param('deposit', 0);
        $customerCount = $this->request->param('customer_count', 1);
        $remark = $this->request->param('remark', '');

        if (empty($carNumber) || empty($planName)) {
            return json(['code' => 400, 'msg' => '参数不完整']);
        }

        try {
            // 验证会员是否完成实名认证
            $customerInfo = Db::name('customerinfo')
                ->where('member_id', $memberId)
                ->find();

            if (!$customerInfo || empty($customerInfo['CustomerName']) || empty($customerInfo['CustomerCard'])) {
                return json(['code' => 400, 'msg' => '请先完成实名认证']);
            }

            // 检查是否存在未完成的订单
            $existingOrder = Db::name('sysordertable')
                ->where('CustOmerCard', $customerInfo['CustomerCard'])
                ->where('OrderStatus', '1') // 1: 已出租
                ->find();

            if ($existingOrder) {
                return json(['code' => 400, 'msg' => '您有未完成的订单，请先结算后再下单']);
            }

            // 验证车辆是否可用
            $carInfo = Db::name('syscarinfo')
                ->where('CarNumber', $carNumber)
                ->find();

            if (!$carInfo) {
                return json(['code' => 404, 'msg' => '车辆不存在']);
            }

            if ($carInfo['CarStatus'] != '1') {
                return json(['code' => 400, 'msg' => '车辆当前不可用']);
            }

            // 验证计费方案
            $billingPlan = Db::name('sysbillingplan')
                ->where('JifeiXiangName', $planName)
                ->find();

            if (!$billingPlan) {
                return json(['code' => 404, 'msg' => '计费方案不存在']);
            }

            // 获取关联的卡信息
            $cardInfo = Db::name('sysidcardinfo')
                ->where('CarNomber', $carNumber)
                ->find();

            // 开启事务
            Db::startTrans();

            try {
                // 生成订单号
                $orderNumber = $this->generateOrderNumber();

                // 创建订单
                $orderData = [
                    'OrderNomber' => $orderNumber,
                    'CustOmerCard' => $customerInfo['CustomerCard'],
                    'CarNomber' => $carNumber,
                    'StarTime' => date('Y-m-d H:i:s'),
                    'CustomYajin' => $deposit,
                    'idCardNomber' => $cardInfo ? $cardInfo['IDCardNomber'] : '',
                    'idCardType' => $cardInfo ? $cardInfo['IDCardType'] : '临时卡',
                    'JiFeiXiangName' => $planName,
                    'CustomerCount' => $customerCount,
                    'ShouKuanType' => Config::get('applet.order.default_payment_type', '现金收款'),
                    'MoneyFlag' => '0', // 未付款
                    'OperationTime' => date('Y-m-d H:i:s'),
                    'OrderStatus' => '1', // 已出租
                    'OperationName' => '小程序用户',
                    'omumiHours' => '0',
                    'zongMoney' => '0',
                    'remark' => $remark,
                    'LockAmonut' => 0,
                    'LockStatus' => 0
                ];

                $orderId = Db::name('sysordertable')->insertGetId($orderData);

                if (!$orderId) {
                    throw new \Exception('订单创建失败');
                }

                // 更新车辆状态为已租出
                $updateCar = Db::name('syscarinfo')
                    ->where('CarNumber', $carNumber)
                    ->update(['CarStatus' => '2']);

                if (!$updateCar) {
                    throw new \Exception('车辆状态更新失败');
                }

                // 如果有卡信息，可以更新卡的使用状态等
                if ($cardInfo) {
                    // 这里可以添加卡状态更新逻辑
                }

                // 提交事务
                Db::commit();

                $orderData['id'] = $orderId;

                return json([
                    'code' => 200,
                    'data' => [
                        'order_info' => $orderData,
                        'billing_plan' => $billingPlan
                    ],
                    'msg' => '订单创建成功'
                ]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '订单创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 结算订单
     * 暂时没用上 需要改的哦，别乱用
     */
    public function settleOrder()
    {
        $orderId = $this->request->param('order_id', '');
        $endTime = $this->request->param('end_time', '');
        $actualFee = $this->request->param('actual_fee', 0);

        if (empty($orderId) || empty($endTime)) {
            return json(['code' => 400, 'msg' => '参数不完整']);
        }

        try {
            // 获取订单信息
            $orderInfo = Db::name('sysordertable')
                ->where('id', $orderId)
                ->find();

            if (!$orderInfo) {
                return json(['code' => 404, 'msg' => '订单不存在']);
            }

            if ($orderInfo['OrderStatus'] != '1') {
                return json(['code' => 400, 'msg' => '订单状态不允许结算']);
            }

            // 计算使用时长
            $startTime = strtotime($orderInfo['StarTime']);
            $endTimeStamp = strtotime($endTime);
            $duration = $endTimeStamp - $startTime;
            $hours = round($duration / 3600, 2);

            // 如果没有传入实际费用，则根据计费方案计算
            if ($actualFee <= 0) {
                $billingPlan = Db::name('sysbillingplan')
                    ->where('JifeiXiangName', $orderInfo['JiFeiXiangName'])
                    ->find();

                if ($billingPlan) {
                    $hourUnit = $billingPlan['HourW1'] ?? 0.5;
                    $unitPrice = $billingPlan['jifeimoney'] ?? 0;
                    $units = ceil($hours / $hourUnit);
                    $actualFee = $units * $unitPrice;
                }
            }

            // 开启事务
            Db::startTrans();

            try {
                // 更新订单信息
                $updateData = [
                    'EndTime' => $endTime,
                    'omumiHours' => $hours . '小时',
                    'zongMoney' => $actualFee,
                    'MoneyFlag' => '1', // 已付款
                    'OrderStatus' => '2', // 结算完毕
                    'OperationTime' => date('Y-m-d H:i:s')
                ];

                $updateOrder = Db::name('sysordertable')
                    ->where('id', $orderId)
                    ->update($updateData);

                if (!$updateOrder) {
                    throw new \Exception('订单更新失败');
                }

                // 更新车辆状态为可用
                $updateCar = Db::name('syscarinfo')
                    ->where('CarNumber', $orderInfo['CarNomber'])
                    ->update(['CarStatus' => '1']);

                if (!$updateCar) {
                    throw new \Exception('车辆状态更新失败');
                }

                // 提交事务
                Db::commit();

                return json([
                    'code' => 200,
                    'data' => [
                        'order_id' => $orderId,
                        'duration_hours' => $hours,
                        'total_fee' => $actualFee,
                        'deposit' => $orderInfo['CustomYajin']
                    ],
                    'msg' => '订单结算成功'
                ]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '订单结算失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取订单详情
     */
    public function getOrderDetail()
    {
        $orderId = $this->request->param('order_id', '');

        if (empty($orderId)) {
            return json(['code' => 400, 'msg' => '订单ID不能为空']);
        }

        try {
            $orderInfo = Db::name('sysordertable')
                ->where('id', $orderId)
                ->find();

            if (!$orderInfo) {
                return json(['code' => 404, 'msg' => '订单不存在']);
            }

            // 获取关联的车辆信息
            $carInfo = Db::name('syscarinfo')
                ->where('CarNumber', $orderInfo['CarNomber'])
                ->find();

            // 获取客户信息
            $customerInfo = Db::name('customerinfo')
                ->where('CustomerCard', $orderInfo['CustOmerCard'])
                ->find();

            // 获取计费方案信息
            $billingPlan = Db::name('sysbillingplan')
                ->where('JifeiXiangName', $orderInfo['JiFeiXiangName'])
                ->find();

            return json([
                'code' => 200,
                'data' => [
                    'order_info' => $orderInfo,
                    'car_info' => $carInfo,
                    'customer_info' => $customerInfo,
                    'billing_plan' => $billingPlan
                ],
                'msg' => '获取成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 获取我的订单列表
     */
    public function getOrderList()
    {
        $memberId = $this->getMemberIdFromToken();

        if (!$memberId) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $status = $this->request->param('status', '');

        try {
            // 获取会员的客户信息
            $customerInfo = Db::name('customerinfo')
                ->where('member_id', $memberId)
                ->find();

            if (!$customerInfo) {
                return json([
                    'code' => 200,
                    'data' => [
                        'list' => [],
                        'count' => 0
                    ],
                    'msg' => '暂无订单'
                ]);
            }

            $query = Db::name('sysordertable')
                ->where('CustOmerCard', $customerInfo['CustomerCard'])
                ->order('id desc');

            if (!empty($status)) {
                $query->where('OrderStatus', $status);
            }

            $list = $query->page($page, $limit)->select();
            $count = $query->count();

            // 补充车辆信息
            foreach ($list as &$item) {
                $carInfo = Db::name('syscarinfo')
                    ->field('CarXingHao,CarBrand,CarColors,CarImages')
                    ->where('CarNumber', $item['CarNomber'])
                    ->find();
                $item['car_info'] = $carInfo;
            }

            return json([
                'code' => 200,
                'data' => [
                    'list' => $list,
                    'count' => $count
                ],
                'msg' => '获取成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 取消订单（仅未开始的订单可取消）
     */
    public function cancelOrder()
    {
        $orderId = $this->request->param('order_id', '');
        $reason = $this->request->param('reason', '');

        if (empty($orderId)) {
            return json(['code' => 400, 'msg' => '订单ID不能为空']);
        }

        try {
            $orderInfo = Db::name('sysordertable')
                ->where('id', $orderId)
                ->find();

            if (!$orderInfo) {
                return json(['code' => 404, 'msg' => '订单不存在']);
            }

            if ($orderInfo['OrderStatus'] != '1') {
                return json(['code' => 400, 'msg' => '订单状态不允许取消']);
            }

            // 开启事务
            Db::startTrans();

            try {
                // 更新订单状态
                $updateOrder = Db::name('sysordertable')
                    ->where('id', $orderId)
                    ->update([
                        'OrderStatus' => '3', // 假设3为已取消状态
                        'remark' => $orderInfo['remark'] . ' [取消原因：' . $reason . ']',
                        'OperationTime' => date('Y-m-d H:i:s')
                    ]);

                if (!$updateOrder) {
                    throw new \Exception('订单状态更新失败');
                }

                // 恢复车辆状态为可用
                $updateCar = Db::name('syscarinfo')
                    ->where('CarNumber', $orderInfo['CarNomber'])
                    ->update(['CarStatus' => '1']);

                if (!$updateCar) {
                    throw new \Exception('车辆状态更新失败');
                }

                // 提交事务
                Db::commit();

                return json(['code' => 200, 'msg' => '订单取消成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '订单取消失败：' . $e->getMessage()]);
        }
    }

    /**
     * 生成订单号
     */
    private function generateOrderNumber()
    {
        $prefix = Config::get('applet.order.prefix', 'SD');
        $timestamp = date('YmdHis');
        $random = sprintf('%03d', mt_rand(100, 999));

        return $prefix . $timestamp . $random;
    }

    /**
     * 从token获取会员ID
     */
    private function getMemberIdFromToken()
    {
        $token = $this->request->header('token', '');

        if (empty($token)) {
            return false;
        }

        return Cache::get('member_token_' . $token);
    }
}
